<template>
  <div class="post-audit-container">
    <a-card :bordered="false" class="audit-card">
      <template #title>
        <div class="audit-header">
          <div class="title">
            <audit-outlined /> 帖子审核管理
          </div>
          <a-space>
            <a-select v-model:value="queryParams.status" style="width: 120px" placeholder="帖子状态" @change="handleStatusChange">
              <a-select-option :value="null">全部状态</a-select-option>
              <a-select-option :value="POST_STATUS.PENDING">待审核</a-select-option>
              <a-select-option :value="POST_STATUS.PUBLISHED">已发布</a-select-option>
              <a-select-option :value="POST_STATUS.REJECTED">已拒绝</a-select-option>
            </a-select>
            <a-button type="primary" @click="fetchPosts">刷新</a-button>
          </a-space>
        </div>
      </template>
      
      <a-table 
        :columns="columns" 
        :data-source="postList" 
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
      >
        <!-- 标题列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'title'">
            <router-link :to="`/post/${record.id}`" class="post-title">{{ record.title }}</router-link>
          </template>
          
          <!-- 状态列 -->
          <template v-else-if="column.dataIndex === 'status'">
            <post-status-tag :status="record.status" />
          </template>
          
          <!-- 操作列 -->
          <template v-else-if="column.dataIndex === 'action'">
            <a-space>
              <a-button 
                v-if="record.status === POST_STATUS.PENDING" 
                type="primary" 
                size="small" 
                @click="approvePost(record)"
              >
                通过
              </a-button>
              <a-button 
                v-if="record.status === POST_STATUS.PENDING" 
                danger 
                size="small" 
                @click="rejectPost(record)"
              >
                拒绝
              </a-button>
              <a-button 
                v-if="record.status === POST_STATUS.REJECTED" 
                type="primary" 
                size="small" 
                @click="approvePost(record)"
              >
                重新审核
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 拒绝原因弹窗 -->
    <a-modal 
      v-model:visible="rejectModalVisible" 
      title="拒绝发布原因" 
      @ok="handleRejectConfirm" 
      :confirmLoading="rejectLoading"
    >
      <a-form :model="rejectForm">
        <a-form-item label="拒绝原因" :rules="[{ required: true, message: '请输入拒绝原因' }]">
          <a-textarea 
            v-model:value="rejectForm.reason" 
            placeholder="请输入拒绝原因，将通知给作者" 
            :rows="4" 
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { AuditOutlined } from '@ant-design/icons-vue';
import PostStatusTag from '@/components/PostStatusTag.vue';
import { POST_STATUS } from '@/constants';
import { useUserStore } from '@/stores/user';
import { storeToRefs } from 'pinia';
import type { TablePaginationConfig } from 'ant-design-vue';
import { 
  getPendingPosts as fetchPendingPosts, 
  getPostsByStatus,
  approvePost as approvePostAPI, 
  rejectPost as rejectPostAPI,
  ApiResponse
} from '@/api/admin';

// 用户信息
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

// 表格配置
const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    ellipsis: true,
  },
  {
    title: '作者',
    dataIndex: 'authorName',
    key: 'authorName',
  },
  {
    title: '分类',
    dataIndex: 'categoryName',
    key: 'categoryName',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    sorter: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    fixed: 'right',
    width: 160,
  }
];

// 状态
const loading = ref(false);
const postList = ref<any[]>([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
});

// 查询参数
const queryParams = reactive({
  status: POST_STATUS.PENDING, // 默认查看待审核的帖子
  pageNum: 1,
  pageSize: 10,
  orderBy: 'createTime,desc',
});

// 拒绝原因模态框
const rejectModalVisible = ref(false);
const rejectLoading = ref(false);
const rejectForm = reactive({
  postId: null as number | null,
  reason: '',
});

// 加载帖子列表
const fetchPosts = async () => {
  loading.value = true;
  try {
    let res: ApiResponse;
    
    console.log('开始获取帖子列表，状态:', queryParams.status);
    
    // 根据状态获取不同的帖子列表
    if (queryParams.status === null) {
      // 获取所有状态的帖子
      console.log('获取所有状态帖子: /api/post/audit/pending');
      res = await fetchPendingPosts(queryParams);
    } else {
      // 获取特定状态的帖子
      console.log(`获取特定状态帖子: /api/post/audit/status/${queryParams.status}`);
      res = await getPostsByStatus(queryParams.status, queryParams);
    }
    
    console.log('获取帖子响应:', res);
    
    // 兼容不同的响应格式
    if (res && (res.code === 200 || res.success === true)) {
      if (Array.isArray(res.data)) {
        postList.value = res.data;
        pagination.total = res.data.length || 0;
      } else if (res.data && Array.isArray(res.data.list)) {
        // 兼容分页响应格式
        postList.value = res.data.list;
        pagination.total = res.data.total || res.data.list.length || 0;
      } else {
        postList.value = [];
        pagination.total = 0;
        console.warn('响应数据格式不符合预期:', res.data);
      }
      message.success('获取帖子列表成功');
    } else {
      postList.value = [];
      message.error(res?.message || '获取帖子列表失败');
    }
  } catch (error: any) {
    console.error('获取帖子列表失败:', error);
    message.error(`获取帖子列表失败: ${error.message || error}`);
    postList.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理表格变化
const handleTableChange = (pag: TablePaginationConfig) => {
  pagination.current = pag.current || 1;
  pagination.pageSize = pag.pageSize || 10;
  queryParams.pageNum = pagination.current;
  queryParams.pageSize = pagination.pageSize;
  fetchPosts();
};

// 处理状态变化
const handleStatusChange = () => {
  queryParams.pageNum = 1;
  pagination.current = 1;
  fetchPosts();
};

// 审核通过帖子
const approvePost = async (record: any) => {
  try {
    if (!userInfo.value?.id) {
      message.error('您需要登录才能执行审核操作');
      return;
    }
    
    const res: ApiResponse = await approvePostAPI(record.id, userInfo.value.id);
    if (res.code === 200) {
      message.success('帖子审核通过');
      fetchPosts();
    } else {
      message.error(res.message || '操作失败');
    }
  } catch (error: any) {
    console.error('审核操作失败:', error);
    message.error(error.message || '审核操作失败');
  }
};

// 打开拒绝弹窗
const rejectPost = (record: any) => {
  rejectForm.postId = record.id;
  rejectForm.reason = '';
  rejectModalVisible.value = true;
};

// 确认拒绝
const handleRejectConfirm = async () => {
  if (!rejectForm.reason.trim()) {
    message.error('请输入拒绝原因');
    return;
  }
  
  if (!userInfo.value?.id) {
    message.error('您需要登录才能执行审核操作');
    return;
  }
  
  rejectLoading.value = true;
  try {
    const res: ApiResponse = await rejectPostAPI(rejectForm.postId!, userInfo.value.id, rejectForm.reason);
    if (res.code === 200) {
      message.success('已拒绝发布该帖子');
      rejectModalVisible.value = false;
      fetchPosts();
    } else {
      message.error(res.message || '操作失败');
    }
  } catch (error: any) {
    console.error('拒绝操作失败:', error);
    message.error(error.message || '操作失败');
  } finally {
    rejectLoading.value = false;
  }
};

onMounted(() => {
  fetchPosts();
});
</script>

<style scoped>
.post-audit-container {
  margin: 24px;
}

.audit-card {
  margin-bottom: 24px;
}

.audit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-title {
  color: #1890ff;
  font-weight: 500;
}

.post-title:hover {
  text-decoration: underline;
}
</style> 